//
//  PPAlbumPictureInsertionViewController.m
//  pickpic
//
//  Created by Jinxiao on 10/2/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAlbumPictureInsertionViewController.h"
#import "PPAlbumContentViewController.h"
#import "PPAssetsPickerViewController.h"
#import "PPAlbumContentPictureViewController.h"


#import "PPAlbumContentTableViewPictureRowCell.h"
#import "PPAlbumContentTableViewPictureAddCell.h"
#import "PPAlbumPictureInsertionTableViewAlbumsCell.h"
#import "PPAlbumEditContentViewController.h"
@interface PPAlbumPictureInsertionViewController () <PPAssetsPickerViewControllerDelegate, PPAlbumContentTableViewPictureRowCellDelegate, PPAlbumContentPictureViewControllerDelegate>
@property (readwrite, nonatomic, strong) NSArray <PPAlbumModel *> *albums;
@property (readwrite, nonatomic, strong) NSMutableSet <NSString *> *selectedAlbumUUIDs;
@end

@implementation PPAlbumPictureInsertionViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    _selectedAlbumUUIDs = [[NSMutableSet alloc] init];

    _albums = [PPAlbumModel where:@{@"deleted": @(NO)}];

    __weak typeof(self)weakSelf = self;
    [self setNavigationLeftTitle:@"取消" titleColor:[UIColor colorWithRGBHex:0xf2f2f2] action:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];

    [self setNavigationRightTitle:@"保存" titleColor:[UIColor colorWithRGBHex:0xffdd17] action:^{
        [weakSelf saveItemDidPressed];
    }];

    [self updateNavigationBar];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self.tableView reloadData];
}

- (void)updateNavigationBar {
    UIBarButtonItem *confirmItem = self.navigationItem.rightBarButtonItem;

    if(_selectedAlbumUUIDs.count == 0) {
        confirmItem.enabled = NO;
        confirmItem.tintColor = [UIColor colorWithRGBHex:0xb2b2b2];
    } else {
        confirmItem.enabled = YES;
        confirmItem.tintColor = [UIColor colorWithRGBHex:0xffdd17];
    }
}

- (void)saveItemDidPressed {
    for(NSString *auuid in _selectedAlbumUUIDs) {
        NSMutableArray *insertedImages = [NSMutableArray array];

        NSString *coverUUID = nil;

        for(PPAbstractArtwork *artwork in _dataSource.insertedImages) {
            BOOL cover = NO;
            if([_dataSource.coverUUID isEqualToString:artwork.uuid]) {
                cover = YES;
            }

            PPAbstractArtwork *newArtwork = [[PPAbstractArtwork alloc] init];
            newArtwork.uuid = [NSString uuid];
            newArtwork.created = YES;
            newArtwork.URLString = artwork.URLString;
            newArtwork.image = artwork.image;
            newArtwork.thumbnail = artwork.thumbnail;
            newArtwork.placeholder = artwork.placeholder;
            newArtwork.asset = artwork.asset;
            newArtwork.desc = artwork.desc;

            [insertedImages addObject:newArtwork];

            if(cover) {
                coverUUID = newArtwork.uuid;
            }
        }

        [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:auuid insertedArtworks:insertedImages modifiedArtworks:nil deletedArtworks:nil tags:nil title:nil description:nil order:nil permission:nil privacy:nil privacyUserIDs:nil coverUUID:coverUUID];
    }

    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch(section) {
        case 0: {
            NSInteger rows = ceil(self.dataSource.images.count/4.0);

            return rows + 2;
        }

        default:
            return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(section == 0) {
        return CGFLOAT_MIN;
    } else {
        return 46;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(section == 0) {
        return CGFLOAT_MIN;
    } else {
        return 6;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if(section == 0) {
        UIView *header = [[UIView alloc] init];
        header.frame = CGRectMake(0, 0, tableView.width, CGFLOAT_MIN);
        header.backgroundColor = [UIColor clearColor];
        return header;
    } else {
        UIView *header = [[UIView alloc] init];
        header.frame = CGRectMake(0, 0, tableView.width, 46);
        header.backgroundColor = [UIColor clearColor];

        UILabel *label = [[UILabel alloc] init];
        label.text = @"选择保存到相册";
        label.textColor = [UIColor colorWithRGBHex:0x323232];
        label.font = [UIFont systemFontOfSize:16];
        [label sizeToFit];
        label.left = 14;
        label.centerY = header.height/2;
        [header addSubview:label];
        return header;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch(indexPath.section) {
        case 0: {
            if(indexPath.row == 0) {
                return 161;
            } else if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1) {
                if(_dataSource.images.count == 0) {
                    return 0;
                } else {
                    return 12;
                }
            } else {
                return [PPAlbumContentTableViewPictureRowCell heightForNumberOfPictures:_dataSource.images.count boundingSize:CGSizeMake(tableView.width, CGFLOAT_MAX)];
            }

            break;
        }

        case 1: {
            return [PPAlbumPictureInsertionTableViewAlbumsCell heightForNumberOfAlbums:_albums.count boundingSize:CGSizeMake(tableView.width, CGFLOAT_MAX)];
        }
    }

    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = nil;

    switch(indexPath.section) {
        case 0: {

            if(indexPath.row == 0) {
                identifier = @"addCell";
                break;
            } else if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1) {
                identifier = @"footerCell";
                break;
            } else {
                identifier = @"pictureCell";
                break;
            }

            break;
        }

        case 1: {
            identifier = @"albumsCell";
            break;
        }

        default:
            break;
    }

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];

    __weak typeof(self)weakSelf = self;

    if([identifier isEqualToString:@"addCell"]) {
        [((PPAlbumContentTableViewPictureAddCell *)cell).addButton setActionBlock:^(UIControl *control) {
            [MobClick event:@"55"];
            PPAssetsPickerViewController *assetsViewController = [[PPAssetsPickerViewController alloc] init];
            assetsViewController.delegate = weakSelf;
            assetsViewController.userInfo = @{@"type" : @"addImage"};
            [weakSelf.navigationController pushViewController:assetsViewController animated:YES];
        } forControlEvents:UIControlEventTouchUpInside];
    } else if([identifier isEqualToString:@"pictureCell"]) {
        NSInteger index = (indexPath.row - 1)*4;
        ((PPAlbumContentTableViewPictureRowCell *)cell).artwork1 = [self.dataSource.images safeObjectAtIndex:index];
        ((PPAlbumContentTableViewPictureRowCell *)cell).artwork2 = [self.dataSource.images safeObjectAtIndex:index + 1];
        ((PPAlbumContentTableViewPictureRowCell *)cell).artwork3 = [self.dataSource.images safeObjectAtIndex:index + 2];
        ((PPAlbumContentTableViewPictureRowCell *)cell).artwork4 = [self.dataSource.images safeObjectAtIndex:index + 3];
    } else if([identifier isEqualToString:@"albumsCell"]) {
        [((PPAlbumPictureInsertionTableViewAlbumsCell *)cell).addButton setActionBlock:^(UIControl *control) {
            [MobClick event:@"56"];
            
            
            PPAlbumEditContentViewController *createViewController = [[PPAlbumEditContentViewController alloc] init];
            
//            PPAlbumContentViewController *createViewController = [[UIStoryboard storyboardWithName:@"Album" bundle:nil] instantiateViewControllerWithIdentifier:@"PPAlbumContentViewController"];
            createViewController.type = PPAlbumContentViewControllerTypeCreate;
            [createViewController.dataSource.images addObjectsFromArray:weakSelf.dataSource.images];
            [createViewController.dataSource.insertedImages addObjectsFromArray:weakSelf.dataSource.insertedImages];
            [weakSelf.navigationController pushViewController:createViewController animated:YES];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([cell respondsToSelector:@selector(setDelegate:)]) {
        [cell performSelector:@selector(setDelegate:) withObject:self];
    }

    if([cell respondsToSelector:@selector(setDataSource:)]) {
        [cell performSelector:@selector(setDataSource:) withObject:self.dataSource];
    }

    if([cell respondsToSelector:@selector(setAlbums:)]) {
        [cell performSelector:@selector(setAlbums:) withObject:self.albums];
    }

    return cell;
}

#pragma mark - PPAlbumPictureInsertionTableViewAlbumsCellDelegate

- (void)albumsCell:(PPAlbumPictureInsertionTableViewAlbumsCell *)albumsCell didChangeSelectionState:(BOOL)selected atIndex:(NSInteger)index {
    NSString *auuid = albumsCell.albums[index].auuid;

    if(selected) {
        [_selectedAlbumUUIDs addObject:auuid];
    } else {
        [_selectedAlbumUUIDs removeObject:auuid];
    }

    [self updateNavigationBar];
}

#pragma mark - PPAlbumContentTableViewPictureRowCellDelegate

- (void)pictureCell:(PPAlbumContentTableViewPictureRowCell *)pictureCell didSelectDeleteButton:(UIButton *)button atIndex:(NSInteger)index {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:pictureCell];

    index = (indexPath.row - 1)*4 + index;

    PPAbstractArtwork *artwork = [_dataSource.images objectAtIndex:index];

    [_dataSource.deletedImages addObject:artwork];
    [_dataSource.images removeObject:artwork];

    [self.tableView reloadData];
}

- (void)pictureCell:(PPAlbumContentTableViewPictureRowCell *)pictureCell didSelectArtworkAtIndex:(NSInteger)index {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:pictureCell];

    index = (indexPath.row - 1)*4 + index;

    PPAlbumContentPictureViewController *pictureViewController = [[PPAlbumContentPictureViewController alloc] init];
    pictureViewController.artworks = _dataSource.images;
    pictureViewController.index = index;
    pictureViewController.delegate = self;
    [self.navigationController pushViewController:pictureViewController animated:YES];
}

#pragma mark - PPAssetsPickerViewControllerDelegate

- (void)assetsPickerViewControllerDidPressCancel:(PPAssetsPickerViewController *)assetsPickerViewController {
    [self.navigationController popToViewController:self animated:YES];
}

- (void)assetsPickerViewControllerDidPressConfirm:(PPAssetsPickerViewController *)assetsPickerViewController {
    [assetsPickerViewController.selectedAssets enumerateObjectsUsingBlock:^(ALAsset *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
        artwork.uuid = [NSString uuid];
        artwork.image = [obj.image fixOrientation];
        artwork.thumbnail = obj.thumbnailImage;
        artwork.created = YES;

        [_dataSource.images addObject:artwork];
        [_dataSource.insertedImages addObject:artwork];

        [self.tableView reloadData];
    }];

    [self.navigationController popToViewController:self animated:YES];
}

#pragma mark - PPAlbumContentPictureViewControllerDelegate

- (void)pictureViewController:(PPAlbumContentPictureViewController *)pictureViewController setArtworkAsCover:(PPAbstractArtwork *)artwork {
    self.dataSource.coverUUID = artwork.uuid;
}

- (void)pictureViewController:(PPAlbumContentPictureViewController *)pictureViewController setDescription:(NSString *)description forArtwork:(PPAbstractArtwork *)artwork {
    artwork.desc = description;

    if(![self.dataSource.modifiedImages containsObject:artwork]) {
        [self.dataSource.modifiedImages addObject:artwork];
    }
}

@end
